import { generateToken, prefix } from './js/config'
import { imapi } from './instance'
export default {
	//用户登录 登录id自带前缀，其他传值需要获取im配置文件前缀
	async login(userID, userName = '', userAvatar) {
		if (!userID) {
			const user = uni.getStorageSync('user')
			if (!user) return { code: 1 }
			userID = user.UserID;
			userName = user.Name;
			userAvatar = user.HeadImgUrl
		}
		userID = prefix + userID.toString()
		console.log(userID);
		uni.setStorageSync('imUserID', userID)
		const token = generateToken(userID)
		const data = await imapi({ name: 'login' }, userID, { userName, token })
		// const log = await imapi({ name: 'uploadLog' })
		if (data.code === 0 && userAvatar) {
			await imapi({ name: 'updateUserAvatarUrl' }, userAvatar)
		}
		return data
	},
	//修改用户名
	async updateUserName(userName) {
		const data = await imapi({ name: 'updateUserName' }, userName)
		return data
	},
	//修改用户头像
	async updateAvatar(userAvatar) {
		const data = await imapi({ name: 'updateUserAvatarUrl' }, userAvatar)
		return data
	},
	//查询用户信息
	async queryUsersInfo(userIDs) {
		if (!Array.isArray(userIDs)) userIDs = [userIDs]
		const userID = uni.getStorageSync('imUserID')
		userIDs.push(userID)
		const data = await imapi({ name: 'queryUsersInfo', attr: 'userList' }, userIDs, { isQueryFromServer: true })
		if (data.code === 0) {
			uni.setStorageSync('imUserInfo', data.data)
		}
		return data
	},
	//登出
	logout() {
		imapi({ name: 'logout' })
	},
	//销毁
	destroy() {
		imapi({ name: 'destroy' })
	}
}